package com.org.manhu.chargehelper.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;

import android.os.Handler;
import android.os.Message;

/**
 * @文件名：Sever.java
 * @包名：com.org.manhu.tool
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2014年12月31日 下午1:42:27、
 *
 * @描述：
 */
public class Sever extends Thread {

	private ServerSocket ss = null;
	private static Sever sever = null;
	private Socket socket;
	private Handler handler;

	public static Sever getInstance() {
		if (sever == null) {
			sever = new Sever();
		}
		return sever;
	}

	private Sever() {
		try {
			ss = new ServerSocket(2048);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	@Override
	public void run() {
		while (true) {
			try {
				if (ss != null) {
					socket = ss.accept();
				} else {
					ss = new ServerSocket(2048);
				}
				if (socket != null) {
					sendMessageToClient(StringUtils.deviceInfo2Json());
					ServerThread st = new ServerThread(socket);
					st.start();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public class ServerThread extends Thread {
		private Socket socket;

		public ServerThread(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			try {
				if (socket == null) {
					socket = ss.accept();
				}
				if (socket.isConnected()) {
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					BufferedReader br = new BufferedReader(
							new InputStreamReader(is));
					PrintStream ps = new PrintStream(os);
					while (true) {
						String temp = br.readLine();// 读取客户端输入的消息
						if (temp.indexOf("heart") != -1) {
							ps.println(StringUtils.convert2HeartJson(DateUtil
									.getDate()));
						} else if (temp.indexOf("BoxInfo") != -1) {
							Map<String, String> map = JsonUtil.parseAll(temp);
							SharedPreferncesUtil.saveBoxInfo(
									ChargeApplication.mApplicationContext, map);
						} else if (temp.indexOf("offlineResource") != -1) {
							FileUtil.save2File("offlineResource", temp);
							List<Map<String, String>> list = JsonUtil
									.parseToList(temp);
							// if (list != null) {
							Message msg = new Message();
							msg.obj = temp;
							msg.what = 1;
							handler.sendMessage(msg);
							ps.println(StringUtils.acceptListSuccess());
							// }
						} else if (temp.indexOf("push") != -1) {
							String path = JsonUtil.getPath(temp);
							Message msg = new Message();
							msg.obj = path;
							msg.what = 2;
							handler.sendMessage(msg);
						} else if (temp.indexOf("refresh") != -1) {
							Message msg = new Message();
							msg.what = 3;
							handler.sendMessage(msg);
						} else {
							ps.println(temp);
						}

						// ps.println(temp);// 服务器端简单处理一下。
						// if (temp.equals("bye")) {
						// 如果客户端输入bye,推出循环结束。
						// break;
						// }
					}
					// ps.close();
					// br.close();
					// socket.close();
				} else {
					// SocketSever.saveException2File("Connected", "连接已断开");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void acceptClientData() {

	}

	/**
	 * @描述：向客户端发送消息
	 * @param message
	 */
	public void sendMessageToClient(String message) {
		OutputStream os;
		try {
			if (socket != null && !socket.isClosed()) {// 如果客户端没有断开就发送数据
				os = socket.getOutputStream();
				PrintStream ps = new PrintStream(os);
				ps.println(message);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 释放端口
	public void close() {
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sever.close();

	}

	/**
	 * @描述：判断socket连接是否断开
	 * @return
	 */
	public boolean isConnected() {
		if (socket == null || socket.isClosed()) {
			return false;
		}
		return true;
	}

}
